using System;
using System.Collections.Specialized;

using Castle.MonoRail.Framework;
using eduSrc.Models;

namespace eduSrc.Web
{
    public class AuthenticationFilter: IFilter
    {
        public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            User _user = (User)context.Session["logonUser"];

            // Sets the principal as the current user
            context.CurrentUser = _user;

            // Checks if it is OK
            if (context.CurrentUser == null ||
                !context.CurrentUser.Identity.IsAuthenticated)
            {
                // Not authenticated, redirect to login
                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("backUrl", context.Url);
                controller.Redirect("login", "loginForm", parameters);

                // Prevent request from continue
                return false;
            }

            // Everything is ok
            return true;
        }
    }
}
